<template>
  <view>
    <l-background has-sub-background />

    <template v-if="type == 2">
      <view id="tab" class="padding-top-30 padding-lr-30 padding-bottom-14 notice-bar">
        <l-notice-bar :type="noticeType" :list="noticeList" />
      </view>
      <scroll-view :style="{height:height+'px'}" scroll-y>
        <view class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14 card">
            <image-model must :data="form" :list="idCardList" @update="update" />
          </view>

          <view class="margin-bottom-14 card">
            <driver-info-model :data="form" :type="type" :driver-id="driverId" :driver-info="driverInfo" @update="update" />
            <id-card-info-model :data="form" :type="type" @update="update" @changeDate="changeDate" />
          </view>

          <view class="margin-bottom-14 card">
            <image-model must :data="form" :list="driverLicenseList" @update="update" />
          </view>

          <view class="card">
            <identity-info-model :data="form" :type="type" @update="update" @changeDate="changeDate" @changeLicenceType="changeLicenceType" />
          </view>
        </view>
      </scroll-view>
    </template>

    <template v-else>
      <view id="tab" class="padding-top-30 padding-lr-30">
        <l-tab-bar type="2" :tabs="tabList" :active-inx.sync="tabInx" />
      </view>

      <scroll-view v-show="tabInx===0" :style="{height:height+'px'}" scroll-y>
        <view class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14">
            <image-model :data="form" :disabled="!(driverInfo.examineStatus == 3 || driverInfo.examineStatus == 0)" :list="idCardList" :must="type == 2" @update="update" />
          </view>

          <view class="margin-bottom-14 card">
            <driver-info-model :data="form" :type="type" :driver-id="driverId" :driver-info="driverInfo" @update="update" />
          </view>

          <view class="margin-bottom-14 card">
            <contact-information-model :data="form" @update="update" @changeDate="changeDate" />
          </view>

          <view v-if="driverInfo.examineStatus == 3 || driverInfo.examineStatus == 0" class="margin-bottom-14 card">
            <id-card-info-model :data="form" :type="type" @update="update" @changeDate="changeDate" />
          </view>
        </view>
      </scroll-view>

      <scroll-view v-show="tabInx===1" :style="{height:height+'px'}" scroll-y>
        <view class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14">
            <image-model :data="form" :disabled="!(driverInfo.examineStatus == 3 || driverInfo.examineStatus == 0)" :list="driverLicenseList" :must="type == 2" @update="update" @showExampleImage="showExampleImage" />
          </view>

          <view class="margin-bottom-14 card">
            <identity-info-model :data="form" :type="type" :disabled="!(driverInfo.examineStatus == 3 || driverInfo.examineStatus == 0)" @update="update" @changeDate="changeDate" @changeLicenceType="changeLicenceType" />
          </view>
        </view>
      </scroll-view>
    </template>
    <safe-area-bottom id="safeBottom" />
    <l-bottom-button :text="buttonText" @click="submit" />

    <example-image :show.sync="exampleImageShow" :info="exampleImageInfo" />
    <licence-type ref="licenceType" :licence="form.licenceType" :show.sync="showLicenceDialog" @confirm="changeNotice" />
    <tui-datetime ref="dateTime" :cancel-color="colorError" :type="2" :show-cancel="!!cancelText" :cancel-text="cancelText" :end-year="2100" :set-date-time="setDateTime" @confirm="setDate" @cancel="setDate" />
  </view>
</template>

<script>
import DriverInfoModel from '../components/driver-info-model/driver-info-model'
import ContactInformationModel from '../components/contact-information-model/contact-information-model'
import IdCardInfoModel from '../components/id-card-info-model/id-card-info-model'
import IdentityInfoModel from '../components/identity-info-model/identity-info-model'
import LicenceType from '../components/licence-type/licence-type'
import colors from '@/common/colors'
import ImageModel from '../../components/image-model/image-model.vue'
import { dateFormat, formVerify, loading } from '@/common/util'
import { getDriverInfo, updateDriverInfo, updateExamineStatus, addDriverV2 } from '../api'
import { name } from '@/common/config'
export default {
  name: 'AddDriver',
  components: {
    DriverInfoModel,
	ImageModel,
    ContactInformationModel,
    IdCardInfoModel,
    IdentityInfoModel,
    LicenceType
  },
  data() {
    return {
      name,
      colorError: colors.colorError,
      height: 0,
      tabList: [
        { title: '基本信息' },
        { title: '证件信息' }
      ],
      tabInx: 0,
      idCardList: [
        { attr: 'idCard1', label: '身份证正面', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/idcard.png' },
        { attr: 'idCard2', label: '身份证反面', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/idcardback.png' }
      ],
      driverLicenseList: [
        { attr: 'licence1', label: '驾驶证正本', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/singshizheng.png', example: true },
        { attr: 'certification', label: '从业资格证', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/zigezheng.png', example: true },
		{ attr: 'thirdYearNotMajorAccidentCert', label: '三年无重大事故证明', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/zigezheng.png', example: true }
	  ],
      exampleImageInfo: '',
      exampleImageShow: false,
      setDateTime: '',
      cancelText: '',
      set: '',
      type: 0,
      showLicenceDialog: false,
      driverId: '',
      driverInfo: {
        examineStatus: 0,
        nickname: '',
        idCardNo: '',
        address: '',
        licenceNo: ''
      },
      form: {
        avatar: '',
        phone: '',
        idCard1: '',
        idCard2: '',
        licence1: '',
        entryDate: '',
        validStartDate: '',
        issueDate: '',
        certification: '',
        idCardValidDateEnd: '',
        validEndDate: '',
        certificationValidDateEnd: '',
        address: '',
        licenceType: '',
        idCardNo: '',
        nickname: '',
        gender: '',
        licenceNo: '',
        emergentName: '',
        emergentPhone: '',
		thirdYearNotMajorAccidentCert:''
      },
      loading: null
    }
  },
  computed: {
    noticeList() {
      if (this.type == 2) {
        const list = []
        if (this.driverInfo.examineStatus === 3) {
          list.push(`审核未通过: ${this.driverInfo.examineReason || ''}`)
        }
        return list.length ? list : [`根据${this.name}旅游客运平台规定，上架车辆的司机必须完善相关信息`]
      }
      return [`根据${this.name}旅游客运平台规定，上架车辆的司机必须完善相关信息`]
    },
    noticeType() {
      return this.driverInfo && this.driverInfo.examineStatus === 3 ? 'error' : 'waring'
    },
    buttonText() {
      if (this.type == 2) return '提交审核'
      else return this.driverId ? '确定' : '添加司机'
    },
    validationList() {
      if (this.type == 2) {
        return [
          { attr: 'phone', test: 'mobile', placeholder: '司机手机号' },
          { attr: 'idCard1', test: '', toast: '请上传身份证正面' },
          { attr: 'idCard2', test: '', toast: '请上传身份证反面' },
          { attr: 'nickname', test: '', placeholder: '请输入姓名' },
          { attr: 'idCardNo', test: '', placeholder: '请输入司机身份证号' },
          { attr: 'idCardValidDateEnd', test: '', toast: '请选择身份证有效截止日期' },
          { attr: 'licence1', test: '', toast: '请上传驾驶证正本' },
		  { attr: 'thirdYearNotMajorAccidentCert', test: '', toast: '请上传三年无重大事故证明' },
          { attr: 'certification', test: '', toast: '请上传从业资格证' },
          { attr: 'licenceNo', test: '', placeholder: '请输入驾驶证号' },
          { attr: 'licenceType', test: '', toast: '请选择准驾车型' },
          { attr: 'issueDate', test: '', toast: '请选择驾驶证初次领证日期' },
          { attr: 'validEndDate', test: '', toast: '请选择驾驶证有效期' },
          { attr: 'certificationValidDateEnd', test: '', toast: '请选择从业资格证有效期' }
        ]
      } else {
        return [
         
          { attr: 'nickname', test: '', toast: '请输入姓名' },
		  { attr: 'phone', test: 'mobile', toast: '请输入司机手机号' },
          { attr: 'idCard1', test: '', toast: '请上传身份证正面' },
          { attr: 'idCard2', test: '', toast: '请上传身份证反面' },
           { attr: 'idCardNo', test: '', toast: '请输入司机身份证号' },
          { attr: 'idCardValidDateEnd', test: '', toast: '请选择身份证有效截止日期' },
        
		  
          { attr: 'licence1', test: '', toast: '请上传驾驶证正本' },
		  { attr: 'thirdYearNotMajorAccidentCert', test: '', toast: '请上传三年无重大事故证明' },
          { attr: 'certification', test: '', toast: '请上传从业资格证' },
          { attr: 'licenceNo', test: '', toast: '请输入驾驶证号' },
          { attr: 'licenceType', test: '', toast: '请选择准驾车型' },
          { attr: 'issueDate', test: '', toast: '请选择驾驶证初次领证日期' },
          { attr: 'validEndDate', test: '', toast: '请选择驾驶证有效期' },
          { attr: 'certificationValidDateEnd', test: '', toast: '请选择从业资格证有效期' }
        ]
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.driverId = options.id
      this.getInfo()
      uni.setNavigationBarTitle({
        title: '编辑司机'
      })
    }
    if (options.type) {
      this.type = options.type
      uni.setNavigationBarTitle({
        title: '审核资料'
      })
    }
  },
  mounted() {
    this.getHeight()
  },
  methods: {
    getHeight() {
      const wHeight = this.sysInfo().windowHeight
      this.getElementInfo('#tab', res => {
        this.height = wHeight - res.height - this.px()
        this.getElementInfo('#safeBottom', res => {
          this.height -= res.height
        })
      })
    },
    update(e) {
      Object.assign(this.form, e)
    },
    // 获取司机详情
    async getInfo() {
      const [err, res] = await getDriverInfo(this.driverId)
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      this.driverInfo = data

      const dates = ['validStartDate', 'issueDate', 'validEndDate']
      Object.keys(this.form).forEach(item => {
        if (dates.includes(item) && this.driverInfo[item]) {
          this.form[item] = dateFormat(this.driverInfo[item].replace(/-/g, '/'))
        } else {
          if (item === 'entryDate' && this.driverInfo.entryDate) this.form.entryDate = this.driverInfo.entryDate.substring(0, this.driverInfo.entryDate.indexOf(' '))
          else this.form[item] = this.driverInfo[item]
        }
      })
      if (this.form.certificationValidDateEnd) {
      		  let index = this.driverInfo.certificationValidDateEnd.indexOf(' ')
      		if (index !== -1) {
      			this.form.certificationValidDateEnd = this.driverInfo.certificationValidDateEnd.substring(0, index)
      		}
      }
      if (data.validStartDate && !data.validEndDate) this.form.validEndDate = '长期'
      if (data.idCardValidDate && !data.idCardValidDateEnd) this.form.idCardValidDateEnd = '长期'
    },
    // 修改日期
    changeDate(attr) {
      if (attr === 'idCardValidDateEnd' || attr === 'validEndDate') {
        this.cancelText = '长期'
      } else {
        this.cancelText = ''
      }

      if (this.form[attr] && this.form[attr] !== '长期') this.setDateTime = this.form[attr]
      else this.setDateTime = dateFormat()

      if (this.set !== attr) this.$refs.dateTime.initData()

      this.set = attr
      this.$refs.dateTime.show()
    },
    // 确认修改的日期
    setDate(e) {
      this.form[this.set] = e ? e.result : '长期'
    },
    // 显示示例图
    showExampleImage(e) {
      this.exampleImageInfo = e.attr
      this.exampleImageShow = true
    },
    // 修改准驾类型
    changeLicenceType() {
      this.$refs.licenceType.formatChecked()
      this.showLicenceDialog = true
    },
    // 确认修改准驾类型
    changeNotice(e) {
      this.form.licenceType = e
    },
    // 表单提交
    async submit() {
      if (formVerify(this.form, this.validationList)) {
        const data = this.copyData(this.form)
        data.autoCompanyUserId = this.login.userId
        if (data.validEndDate) data.validStartDate = '2020-03-24'
        if (data.idCardValidDateEnd) data.idCardValidDate = '2020-03-24'
        if (data.validEndDate === '长期') data.validEndDate = ''
        else if (data.validEndDate) data.validEndDate += ' 23:59'
        if (data.idCardValidDateEnd === '长期') data.idCardValidDateEnd = ''
        if (data.certificationValidDateEnd) data.certificationValidDateEnd += ' 23:59'
        if (this.type == 2 && !this.checkDate(data)) return false

        let msg
        let err
        let res
        this.loading = loading('提交中')
		if(data.licenceNo && data.idCardNo.length != 18){
			 this.toast('请输入18位身份证号！')
			 return
		}
        if(data.licenceNo && data.licenceNo.length != 18){
			 this.toast('请输入18位驾驶证号！')
			 return
		}
        if (this.type == 2) {
          // 提交审核
          [err, res] = await this.audit(data)
          msg = '提交审核成功'
        } else if (this.driverId) {
          // 修改司机
          [err, res] = await updateDriverInfo(this.driverId, data)
          msg = '修改成功'
        } else {
          // 新增司机
          [err, res] = await addDriverV2(data)
          msg = '添加成功'
        }
        this.loading.hide()
        if (!this.$http.errorCheck(err, res)) return false

        this.toast(msg, () => {
          if (this.driverId) {
            this.jump('/pages/driver/driver', 'switchTab')
          } else {
            this.jump()
          }
        })
      }
    },
    // 日期校验
    checkDate(data) {
      if (data.validEndDate && !this.compare(data.validEndDate)) {
        this.toast('驾驶证已到期，不符合上路标准')
        return false
      }
      if (!this.compare(data.certificationValidDateEnd)) {
        this.toast('道路运输从业资格证已到期，不符合上路标准')
        return false
      }
      return true
    },
    // 日期对比
    compare(date2) {
      const date = typeof date2 === 'number' ? date2 : date2.replace(/-/g, '/')
      const dates1 = new Date().getTime()
      const dates2 = new Date(date).getTime()
      if (dates1 < dates2) {
        return true
      } else {
        return false
      }
    },
    // 提交审核
    async audit(data) {
      const [err, res] = await updateDriverInfo(this.driverId, data)
      if (!this.$http.errorCheck(err, res, false, false, false)) {
        this.loading.hide()
        return false
      }

      return await updateExamineStatus({
        examineReason: '',
        id: this.driverInfo.id,
        examineStatus: 1
      })
    }
  }
}
</script>

<style scoped lang="scss">
@include setPadding(bottom,14);
</style>
